package com.cloudweb.oa.controller;

import cn.js.fan.util.ResKeyException;
import cn.js.fan.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.security.AuthUtil;
import com.cloudweb.oa.vo.Result;
import com.cloudwebsoft.framework.db.JdbcTemplate;
import com.redmoon.oa.flow.FormDb;
import com.redmoon.oa.flow.FormParser;
import com.redmoon.oa.flow.FormViewDb;
import com.redmoon.oa.flow.FormViewMgr;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Vector;

@RestController
@RequestMapping("/formView")
public class FormViewController {

    @Autowired
    HttpServletRequest request;

    @Autowired
    AuthUtil authUtil;

    @ApiOperation(value = "创建视图", notes = "创建视图", httpMethod = "POST")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST, produces = {"text/html;", "application/json;charset=UTF-8;"})
    public Result<Object> create() {
        FormViewMgr ftm = new FormViewMgr();
        boolean re;
        try {
            re = ftm.create(request);
        } catch (ResKeyException e) {
            return new Result<>(false, e.getMessage(request));
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "保存视图", notes = "保存视图", httpMethod = "POST")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = {"text/html;", "application/json;charset=UTF-8;"})
    public Result<Object> update() {
        FormViewMgr ftm = new FormViewMgr();
        boolean re;
        try {
            re = ftm.modify(request);
        } catch (ResKeyException e) {
            return new Result<>(false, e.getMessage(request));
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "删除视图", notes = "删除视图", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/del", method = RequestMethod.POST, produces = {"text/html;", "application/json;charset=UTF-8;"})
    public Result<Object> del(@RequestParam Integer id) {
        boolean re;
        try {
            FormViewDb fvd = new FormViewDb();
            fvd = fvd.getFormViewDb(id);
            re = fvd.del();
        } catch (ResKeyException e) {
            return new Result<>(false, e.getMessage(request));
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "批量删除视图", notes = "批量删除视图", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ids", required = true, dataType = "String"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/delBatch", method = RequestMethod.POST, produces = {"text/html;", "application/json;charset=UTF-8;"})
    public Result<Object> delBatch(@RequestParam String ids) {
        boolean re = false;
        try {
            String[] ary = ids.split(",");
            FormViewDb fvd = new FormViewDb();
            for (String strId : ary) {
                int id = StrUtil.toInt(strId);
                fvd = fvd.getFormViewDb(id);
                re = fvd.del();
            }
        } catch (ResKeyException e) {
            return new Result<>(false, e.getMessage(request));
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "获取视图", notes = "获取视图", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/getViewById", method = RequestMethod.POST, produces = {"text/html;", "application/json;charset=UTF-8;"})
    public Result<Object> getViewById(Integer id) {
        FormViewDb formViewDb = new FormViewDb();
        formViewDb = formViewDb.getFormViewDb(id);
        JSONObject json = new JSONObject();
        json.put("id", id);
        json.put("name", formViewDb.getString("name"));
        json.put("content", formViewDb.getString("content"));
        json.put("formCode", formViewDb.getString("form_code"));
        return new Result<>(json);
    }

    @ApiOperation(value = "列出视图", notes = "列出视图", httpMethod = "POST")
    @RequestMapping(value = "/list", produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    @ResponseBody
    public Result<Object> list(@RequestParam String formCode, @RequestParam(defaultValue = "") String name) {
        FormViewDb formViewDb = new FormViewDb();
        Vector<FormViewDb> formV = formViewDb.list(formCode, "search", name);
        com.alibaba.fastjson.JSONArray arr = new JSONArray();
        for (FormViewDb formViewDb1 : formV) {
            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            json.put("id", formViewDb1.getInt("id"));
            json.put("name", formViewDb1.getString("name"));
            arr.add(json);
        }
        return new Result<>(arr);
    }

    @ApiOperation(value = "取得显示规则", notes = "取得显示规则", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/getViewRule", method = RequestMethod.POST, produces = {"text/html;", "application/json;charset=UTF-8;"})
    public Result<Object> getViewRule(Integer id) {
        FormViewDb formViewDb = new FormViewDb();
        formViewDb = formViewDb.getFormViewDb(id);
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("views", formViewDb.getString("show_rule"));
        return new Result<>(json);
    }

    @ApiOperation(value = "保存显示规则", notes = "保存显示规则", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "viewSetup", value = "显示规则", required = true, dataType = "String"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/updateViewSetup", method = RequestMethod.POST, produces = {"text/html;", "application/json;charset=UTF-8;"})
    public Result<Object> updateViewSetup(Integer id, String viewSetup) {
        FormViewDb formViewDb = new FormViewDb();
        formViewDb = formViewDb.getFormViewDb(id);
        formViewDb.set("show_rule", viewSetup);
        boolean re;
        try {
            re = formViewDb.save();
        } catch (ResKeyException e) {
            return new Result<>(false, e.getMessage(request));
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "取出视图中的元素", notes = "取出视图中的元素", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer"),
    })
    @RequestMapping(value = "/getElements", produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    @ResponseBody
    public Result<Object> getElements(@RequestParam Integer id) {
        FormViewDb formViewDb = new FormViewDb();
        formViewDb = formViewDb.getFormViewDb(id);

        String code = formViewDb.getString("form_code");
        FormDb fd = new FormDb();
        fd = fd.getFormDb(code);
        com.alibaba.fastjson.JSONArray ary = FormParser.parseElementFromView(request, formViewDb, fd);
        for (int i = 0; i < ary.size(); i++) {
            com.alibaba.fastjson.JSONObject json = ary.getJSONObject(i);
            String objId = json.getString("id");
            String objName = json.getString("name");
            if ("".equals(objId)) {
                objId = objName;
            }
            String objTitle = json.getString("title");
            if ("".equals(objTitle)) {
                if (!"".equals(objName)) {
                    objTitle = objName;
                } else {
                    objTitle = objId;
                }
            }

            String tagName = json.getString("tagName");
            switch (tagName) {
                case "tr":
                    tagName = "表格行";
                    break;
                case "input":
                    tagName = "字段";
                    break;
                case "div":
                    tagName = "区块元素";
                    break;
                case "span":
                    tagName = "行内元素";
                    break;
                case "":
                    tagName = "元";
                    break;
            }

            String tagTitle = tagName + ": " + objTitle + "(" + objId + ")";
            json.put("tagTitle", tagTitle);
            json.put("tagId", objId);
        }
        return new Result<>(ary);
    }

    @ApiOperation(value = "创建表单的默认视图", notes = "创建表单的默认视图", httpMethod = "POST")
    @ApiImplicitParam(name = "formCode", value = "表单编码", required = false, dataType = "String")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/generateDefaultView", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;"})
    public Result<Object> generateDefaultView(String formCode) {
        FormDb fd = new FormDb();
        fd = fd.getFormDb(formCode);
        FormParser formParser = new FormParser();
        String content = formParser.generateDefaultFormView(fd.getContent());
        String form = formParser.generateView(content, "", formCode);
        FormViewDb fvd = new FormViewDb();
        boolean re;
        try {
            int size = fvd.list(formCode, "", "").size();
            String title;
            if (size == 0) {
                title = "默认视图";
            } else {
                title = "默认视图" + (size + 1);
            }
            re = fvd.create(new JdbcTemplate(), new Object[]{formCode, title, content, "1", fd.isHasAttachment() ? 1 : 0, authUtil.getUserName(), new java.util.Date(), "", form});
        } catch (ResKeyException e) {
            return new Result<>(false, e.getMessage(request));
        }
        return new Result<>(re);
    }
}
